package models

import (
	"gitee.com/Hu-Lyndon/distill-resk/infra/db"
	"gitee.com/Hu-Lyndon/distill-resk/infra/utils/supports"
	"github.com/go-xorm/xorm"
	"time"
)

type UserApp struct {
	UserId       int       `json:"user_id" xorm:"not null pk autoincr comment('用户id') INT(11)"`
	UserName     string    `json:"user_name" xorm:"not null comment('用户名称') VARCHAR(30)"`
	UserDesc     string    `json:"user_desc" xorm:"comment('用户描述') VARCHAR(60)"`
	Pwd          string    `json:"pwd" xorm:"comment('密码') VARCHAR(32)"`
	Name         string    `json:"name" xorm:"comment('姓名') VARCHAR(50)"`
	PhoneNo      string    `json:"phone_no" xorm:"comment('手机号码') VARCHAR(15)"`
	Email        string    `json:"email" xorm:"comment('邮件') VARCHAR(30)"`
	CreatedAt    time.Time `json:"created_at" xorm:"default 'CURRENT_TIMESTAMP' comment('创建时间') TIMESTAMP"`
	CreatePerson string    `json:"create_person" xorm:"comment('创建人') VARCHAR(30)"`
	UpdatedAt    time.Time `json:"updated_at" xorm:"default 'CURRENT_TIMESTAMP' comment('更新时间') TIMESTAMP"`
	UpdatePerson string    `json:"update_person" xorm:"comment('更新人') VARCHAR(30)"`
	Enable       int       `json:"enable" xorm:"comment('开启') TINYINT(1)"`
}

//func CreateUser(dbEngines *conf.DBEngines, user ...*User) (int64, error) {
func CreateUser(user ...*UserApp) (int64, error) {
	return db.EngineGroup().Insert(user)
}


func GetUserByUsername(user *UserApp) (bool, error) {
	return db.EngineGroup().Get(user)
}

func GetUsersByUids(uids []int64, page *supports.Pagination) ([]*UserApp, int64, error) {
	users := make([]*UserApp, 0)

	s := db.EngineGroup().In("id", uids).Limit(page.Limit, page.Start)
	count, err := s.FindAndCount(&users)
	return users, count, err
}

func UpdateUserById(user *UserApp) (int64, error) {
	return db.EngineGroup().Id(user.UserId).Update(user)
}

func DeleteByUsers(uids []int64) (effect int64, err error) {
	u := new(UserApp)
	for _, v := range uids {
		i, err1 := db.EngineGroup().Id(v).Delete(u)
		effect += i
		err = err1
	}
	return
}

func GetPaginationUsers(page *supports.Pagination) ([]*UserApp, int64, error) {
	var (
		session  *xorm.Session
		err      error
		count    int64
		userList = make([]*UserApp, 0)
	)

	session = db.EngineGroup().Limit(page.Limit, page.Start)
	err = session.Find(&userList)
	count, err = session.Count(&UserApp{})

	return userList, count, err
}
